package com.crazymo.activitybganim;

import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Toast;

import com.crazymo.activitybganim.widget.CustomVideoView;

public class MainActivity extends AppCompatActivity {
    //创建播放视频的控件对象
    private CustomVideoView mVideoView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setFullScreen();
        setContentView(R.layout.activity_main);
        initView();
    }

    private void setFullScreen() {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
    }

    @Override
    protected void onRestart() {
        //返回时重新加载视频，防止退出或返回时视频黑屏
        initView();
        super.onRestart();
    }

    @Override
    protected void onPause() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            mVideoView.stopNestedScroll();
        }
        super.onPause();
    }

    //防止锁屏或者切出的时候，音乐在播放
    @Override
    protected void onStop() {
        if(mVideoView !=null) {
            mVideoView.stopPlayback();
        }
        super.onStop();
    }

    private void initView() {
        mVideoView =  findViewById(R.id.videoview);
        //设置将要播放视频文件的加载路径仅支持 3gp、MP4、avi
        mVideoView.setVideoURI(Uri.parse("android.resource://" + getPackageName() + "/" +R.raw.bg));//此处播放/res/raw下，也可以播放其他路径的调用对应的方法设置即可
        mVideoView.requestFocus();
        mVideoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                if (mp.isPlaying()) {
                    mp.stop();
                    mp.release();
                    mp = new MediaPlayer();
                }
                mp.setVolume(0f, 0f);//设置0,0为静音时
                mp.setLooping(true);
                mp.start();
            }
        });
        mVideoView.setFocusable(false);
        mVideoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mediaPlayer) {
                mVideoView.start();
            }
        });
    }

    public void test(View view) {
        Toast.makeText(this,"在背景视频上点击按钮",Toast.LENGTH_SHORT).show();
    }
}
